/*ram([tasma_in],[caly_program],[aktualne_polecenie,parametr],Akumulator,[[indeX_w_pamieci,wartosc]],[tasma_out],licznik_polecen) nth,select

przykladowe wywolanie
ram1([5,1],[[read_,1],[read_,2],[load_,1],[sub_,2],[store_,3],[write_,3],[jgtz_,3],[halt_,1]],_,_,_,_).*/

        
ram1(L1,L2,A,M,L3,C):-
        nth0(C,L2,E),
        ram(L1,L2,E,A,M,L3,C).
        
ram([H|T],L2,[read_,X],A,[],L3,C):-
        C2 is C+1,
        nth0(C2,L2,E),
        ram(T,L2,E,A,[[X,H]],L3,C2).    
ram([H|T],L2,[read_,X],A,M,L3,C):-
        C2 is C+1,
        nth0(C2,L2,E),
        ram(T,L2,E,A,[[X,H]|M],L3,C2).
        
ram(L,L2,[write_,X],A,M,[],C):-
        szukaj(X,M,E),
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,A,M,E,C2).  
ram(L,L2,[write_,X],A,M,L1,C):-
        szukaj(X,M,E),
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,A,M,[E|L1],C2).     
        
ram(L,L2,[load_,X],_,M,L1,C):-
        szukaj(X,M,E),
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,E,M,L1,C2).
        
ram(L,L2,[store_,X],A,M,L1,C):-
        C2 is C+1,
        nth0(C2,L2,E),
        ram(L,L2,E,A,[[X,A]|M],L1,C2).
        
ram(L,L2,[add_,X],A,M,L1,C):-
        szukaj(X,M,E),
        A1 is A+E,
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,A1,M,L1,C2).

ram(L,L2,[sub_,X],A,M,L1,C):-
        szukaj(X,M,E),
        A1 is A-E,
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,A1,M,L1,C2).
        
ram(L,L2,[mult_,X],A,M,L1,C):-
        szukaj(X,M,E),
        A1 is A*E,
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,A1,M,L1,C2).
        
ram(L,L2,[div_,X],A,M,L1,C):-
        szukaj(X,M,E),
        A1 is A//E,
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,A1,M,L1,C2).
        
ram(L,L2,[jgtz_,X],A,M,L1,_):-
        A > 0,
        nth0(X,L2,E2),
        ram(L,L2,E2,A,M,L1,X).
        
ram(L,L2,[jgtz_,_],A,M,L1,C):-
        A =< 0,
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,A,M,L1,C2).
        
ram(L,L2,[jmpz_,X],A,M,L1,_):-
        A =< 0,
        nth0(X,L2,E2),
        ram(L,L2,E2,A,M,L1,X).
        
ram(L,L2,[jmpz_,_],A,M,L1,C):-
        A > 0,
        C2 is C+1,
        nth0(C2,L2,E2),
        ram(L,L2,E2,A,M,L1,C2).
        
ram(L,L2,[jump,X],A,M,L1,C):-
        nth0(X,L2,E2),
        ram(L,L2,E2,A,M,L1,X).
        
ram(_,_,[halt_,_],A,M,L,_):-
        write('Pamiec '), 
        writeln(M),
        write('Wyjscie '),
        writeln(L),
        write('Akumulator '),
        write(A).
        
szukaj(X,[[X1,E]|_],E):-
        X1 = X,!.
szukaj(X,[[X1,_]|T],E):-
        X1 \=  X,
        szukaj(X,T,E).
szukaj(_,[],_).
        

        

        
        



        
        
